package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Sound;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Slf4j
@DubboService
public class SoundApiImpl implements SoundApi {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public ObjectId save(Sound sound) {
        //1.设置属性
        sound.setSid(idWorker.getNextId("sound"));
        sound.setCreated(System.currentTimeMillis());

           Query query = Query.query(Criteria.where("userId").is(sound.getUserId()).and("date").is(sound.getDate()));
           long count = mongoTemplate.count(query, Sound.class);
               if (count < 10) {
               mongoTemplate.save(sound);
           }
         return sound.getId();
    }

    @Override
    public Sound queryStem(Long sid) {
        Query query = Query.query(Criteria.where("sid").is(sid));
        return mongoTemplate.findOne(query,Sound.class);
    }

    @Override
    public List<Sound> findByIds(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query,Sound.class);
    }

    @Override
    public List<Sound> findBySids(Long userId) {
        Query query = Query.query(Criteria.where("userId").nin(userId));
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);
        return soundList;
    }


}
